package com.photoeditor.demo.ui.widget.oldify;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;

import java.lang.ref.WeakReference;
import java.util.Arrays;

/**
 * @author lyzirving
 * time        2019/1/8
 * email       lyzirving@sina.com
 * information
 */
public class OldifyDecoration {

    private Context mContext;
    private WeakReference<Bitmap> mSrcReference;
    private int mDrawableId = -1;
    private float[] mBounds;//x、y pairs of 4 vertexs
    private Matrix mMatrix;

    public OldifyDecoration(Context context, int drawableId) {
        mContext = context;
        mDrawableId = drawableId;
        init();
    }

    private void init() {
        mMatrix = new Matrix();
        Bitmap tmp = BitmapFactory.decodeResource(mContext.getResources(), mDrawableId);
        mBounds = new float[]{
                0, 0, //left top point
                tmp.getWidth(), 0, //right top point
                tmp.getWidth(), tmp.getHeight(), //right bottom point
                0, tmp.getHeight() //left bottom point
        };
        mSrcReference = new WeakReference<>(Bitmap.createBitmap(tmp, 0, 0, tmp.getWidth(), tmp.getHeight()));
        tmp.recycle();
    }

    private Bitmap reload() {
        return BitmapFactory.decodeResource(mContext.getResources(), mDrawableId);
    }

    private void updateBounds(float[] dst) {
        mBounds = Arrays.copyOf(dst, dst.length);
    }

    public void drawSelft(Canvas canvas, Paint paint) {
        Bitmap bmp = mSrcReference.get();
        if (bmp == null || bmp.isRecycled()) {
            bmp = reload();
            mSrcReference = new WeakReference<>(bmp);
        }
        canvas.drawBitmap(bmp, mBounds[0], mBounds[1], paint);
    }

    public void translate2SpecifiedPoint(float left, float top) {
        float originalLeft = mBounds[0];
        float originalTop = mBounds[1];
        float dx = left - originalLeft;
        float dy = top - originalTop;
        float[] dst = new float[8];
        mMatrix.reset();
        mMatrix.setTranslate(dx, dy);
        mMatrix.mapPoints(dst, mBounds);
        updateBounds(dst);
    }

    public void scale(float scaleX, float scaleY) {
        float[] dst = new float[8];
        mMatrix.reset();
        mMatrix.setScale(scaleX, scaleY);
        mMatrix.mapPoints(dst, mBounds);
        updateBounds(dst);
    }

    public float getWidth() {
        return mBounds[2] - mBounds[0];
    }

    public float getHeight() {
        return mBounds[5] - mBounds[1];
    }

    public void destroy() {
        mContext = null;
    }

}
